define(['WebPDF', './RectUtils'], function(WebPDF, RectUtils) {
	'use strict';
	WebPDF.factory('ToolHandlerManager', [function(){
		var _toolHandlerList = [];		
		var _pageContainer;

		var ignoreMouseEventElementList = [];

		function ptInClientRect(pageX, pageY){
			var clientRect = RectUtils.getClientRect(_pageContainer);			
			return RectUtils.ptInRect(clientRect, pageX, pageY);	
		}

		function _bindMouseEvent(pageContainer) {				
			_pageContainer = pageContainer;
			pageContainer.on("mousedown", function(event) {							
				if 	(!ptInClientRect(event.pageX, event.pageY)) return;
				if (event.which === 1 ) {
					var _event = $.extend({}, event);
				 	_event.type = 'lbuttondown.pdf';				 				 
                    pageContainer.trigger(_event);
                }    
                //event.preventDefault();
			})
			.on("mousemove", function(event) {
				var _event = $.extend({}, event);
                _event.type = 'mousemove.pdf';	            	
                pageContainer.trigger(_event);
            })
            .on("mouseup", function(event) {            	
            	if 	(!ptInClientRect(event.pageX, event.pageY)) return;
            	if (event.which === 1 ) {
            		var _event = $.extend({}, event);
            		_event.type = 'lbuttonup.pdf';	            	
                	pageContainer.trigger(_event);
           		}
           		//event.preventDefault();
            })
            .on("mouseleave", function(event) {
                //pageContainer.triggeronMainFrmMouseLeave(event);
            })
            .on("mouseout", function(event) {
                //_self.onMainFrmMouseOut(event);
            });   

            while(ignoreMouseEventElementList.length>0){
            	addIgnoreMouseEventElement(ignoreMouseEventElementList.pop());
            }
		}

		function addIgnoreMouseEventElement(selector) {
			if (_pageContainer){				
				_pageContainer.on("mousedown", selector, _stopPropagation);
			}
			else{
				ignoreMouseEventElementList.push(selector);
			}
		}


		function _stopPropagation(event){            	
            event.stopPropagation();
        }

		WebPDF.PageContainerCreated(function(event, data) {
			_bindMouseEvent(data.pageContainer);
			toolHandlerManager.setCurrentToolByName("handTool");
		});


		var toolHandlerManager = {
			setCurrentToolByName : function(toolName) {					
				if (_pageContainer && _pageContainer.length === 0) return;				

				angular.forEach(_toolHandlerList, function(value, key) {
					value.active(toolName, _pageContainer);
				});				
			},

			registerToolHandler : function(toolHandler) {				
				_toolHandlerList.push(toolHandler);
			},
			'addIgnoreMouseEventElement': addIgnoreMouseEventElement			
		};
		return toolHandlerManager;
	}]);
});